package com.example.mapsapp;

import java.io.ByteArrayInputStream;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Spinner;
import android.widget.Toast;

public class Friends extends Activity{
	
	protected EditText input;
	protected String friendName;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.friend_activity);

		String[] items = {"Friends", "Requests"};
		
		Spinner s = (Spinner) findViewById(R.id.spinnerfriends);
		
		s.setAdapter(new ArrayAdapter(this, android.R.layout.simple_spinner_item, items));
		
		s.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
			
			@Override
			public void onNothingSelected(AdapterView v){
				
			}
			
			@Override
			public void onItemSelected(AdapterView av, View v, int i, long l){
				try{
					new GetFriendsTask().execute();
				}catch (Exception e){
					e.printStackTrace();
				}
			}
			
		});
		
		try{
			new GetFriendsTask().execute();
		}catch (Exception e){
			e.printStackTrace();
		}
		
		
	}
	
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
	    MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.friend_activity, menu);
	    return true;
	}
	
	   public boolean onOptionsItemSelected(MenuItem item) {
		    switch(item.getItemId())
		    {
		    case R.id.addFriend:
		    	addFriend();
				return true;
		    	

			}
			return true;
		}
	   
	   
	   public void addFriend(){{

		   Context context = this;
		   AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
	 
				// set title
				alertDialogBuilder.setTitle("Add Friend");
	 
				// set dialog message
				alertDialogBuilder
					.setMessage("User Name: ")
					.setPositiveButton("Enter",new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog,int id) {
							// if this button is clicked, close
							// current activity
							String friend = input.getText().toString();
							
							new SendFriendRequestTask().execute(friend);
							
							
							dialog.cancel();
						}
					  });
				//EditText input = (EditText) findViewById(R.id.frienddialogtext);
				input = new EditText(this);
				alertDialogBuilder.setView(input);
					// create alert dialog
					AlertDialog alertDialog = alertDialogBuilder.create();
	 
					// show it
					alertDialog.show();
				}
			
	   }
	   
	   
	   


		public class GetFriendsTask extends AsyncTask<String, String, String> {
			@Override
			protected String doInBackground(String... params) {
				// TODO: attempt authentication against a network service.
				String response = "";
				ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
				NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
				
				if(networkInfo != null && networkInfo.isConnected())
				{
					ArrayList<NameValuePair> n = new ArrayList<NameValuePair>(1);
					n.add(new BasicNameValuePair("user", Login.user));
					System.out.println("USER: "+Login.user);
					
					HttpClient httpClient = new DefaultHttpClient();
					HttpPost httppost = new HttpPost("http://softeng.cs.uwosh.edu/students/cs342g2/getFriends.php");
					try
					{
						httppost.setEntity(new UrlEncodedFormEntity(n));
						ResponseHandler<String> respondHandler = new BasicResponseHandler();
						response = httpClient.execute(httppost, respondHandler);
					}
					catch(Exception e){
						
					}
				}
				return response;
			}
			
			@Override
			protected void onPostExecute(String resp){
				
				System.out.println("XML RESP:");
				System.out.println(resp);
				
				Spinner spinner = (Spinner) findViewById(R.id.spinnerfriends);
				boolean friendsSelected = (spinner.getSelectedItemId() == 0);
				 
				try {
					//System.out.println("RESP:" + resp);
					DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
					DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
					Document doc = dBuilder.parse(new ByteArrayInputStream(resp.getBytes()));
					
					 
					doc.getDocumentElement().normalize();
				 
					//System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
					NodeList nList;
					if(friendsSelected){
						nList = doc.getElementsByTagName("friend");
					}else{
						nList = doc.getElementsByTagName("request");
					}
					
					ArrayList<String> list = new ArrayList<String>();
				 
					//System.out.println("----------------------------");
					for (int i = 0; i < nList.getLength(); i++) {
						
						Node nNode = nList.item(i);
				 
						//System.out.println("Current Element :" + nNode.getNodeName());
						if (nNode.getNodeType() == Node.ELEMENT_NODE) {
				 
							Element ele = (Element) nNode;
							
							String friend = ele.getTextContent();
							list.add(friend);
							
							//System.out.println("MESSAGE: " + eElement.getTextContent());
				 
						}
					}
					ListView friendList = (ListView) findViewById(R.id.listFriends);
					ArrayAdapter<String> ad = new ArrayAdapter<String>(Friends.this, android.R.layout.simple_list_item_1, list);
					friendList.setAdapter(ad);
					friendList.setOnItemClickListener(new OnItemClickListener() {
			            public void onItemClick(AdapterView<?> arg0, View view, int position, long index) {
			            	//Do something on click
			            }
			        });
					
					friendList.setOnItemClickListener(new OnItemClickListener(){

						@Override
						public void onItemClick(AdapterView<?> arg0, View arg1,	int arg2, long arg3) {
							ListView list = (ListView) findViewById(R.id.listFriends);
							Spinner s = (Spinner) findViewById(R.id.spinnerfriends);
							boolean friendsSelected = (s.getSelectedItemId() == 0);
							
							friendName = list.getItemAtPosition(arg2).toString();
							
							if(friendsSelected){


								   AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(Friends.this);
							 
										// set title
										alertDialogBuilder.setTitle("View Friend Locaton?");
							 
										// set dialog message
										alertDialogBuilder
											.setMessage("View " + friendName + "'s location?")
											.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
												public void onClick(DialogInterface dialog,int id) {
													// if this button is clicked, close
													// current activity
													
													
													new ViewFriendLocationTask().execute(friendName);
													
													
													dialog.cancel();
												}
											  })
											  .setNegativeButton("No",new DialogInterface.OnClickListener() {
													public void onClick(DialogInterface dialog,int id) {
														
														
														dialog.cancel();
													}
												  });
										//EditText input = (EditText) findViewById(R.id.frienddialogtext);
											// create alert dialog
											AlertDialog alertDialog = alertDialogBuilder.create();
							 
											// show it
											alertDialog.show();
										
								
							}else{
								
								

								   AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(Friends.this);
							 
										// set title
										alertDialogBuilder.setTitle("Accept Friend?");
							 
										// set dialog message
										alertDialogBuilder
											.setMessage("Accept " + friendName + "?")
											.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
												public void onClick(DialogInterface dialog,int id) {
													// if this button is clicked, close
													// current activity
													
													
													new AcceptFriendRequestTask().execute(friendName);
													
													
													dialog.cancel();
												}
											  })
											  .setNegativeButton("No",new DialogInterface.OnClickListener() {
													public void onClick(DialogInterface dialog,int id) {
														
														
														dialog.cancel();
													}
												  });
										//EditText input = (EditText) findViewById(R.id.frienddialogtext);
											// create alert dialog
											AlertDialog alertDialog = alertDialogBuilder.create();
							 
											// show it
											alertDialog.show();
								}
									
							}
							
						});
					
				} catch (Exception e) {
					e.printStackTrace();
			    }
			}
		}


		public class SendFriendRequestTask extends AsyncTask<String, String, String> {
			@Override
			protected String doInBackground(String... params) {
				// TODO: attempt authentication against a network service.
				String response = "";
				ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
				NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
				
				if(networkInfo != null && networkInfo.isConnected())
				{
					ArrayList<NameValuePair> n = new ArrayList<NameValuePair>(1);
					n.add(new BasicNameValuePair("user", Login.user));
					n.add(new BasicNameValuePair("friend", params[0]));
				
					System.out.println("TRYING TO REQUEST: " + params[0]);
					
					HttpClient httpClient = new DefaultHttpClient();
					HttpPost httppost = new HttpPost("http://softeng.cs.uwosh.edu/students/cs342g2/requestFriend.php");
					try
					{
						httppost.setEntity(new UrlEncodedFormEntity(n));
						ResponseHandler<String> respondHandler = new BasicResponseHandler();
						response = httpClient.execute(httppost, respondHandler);
					}
					catch(Exception e){
						
					}
				}
				return response;
			}
			
			@Override
			protected void onPostExecute(String resp){
				try {
					Toast.makeText(Friends.this, "Request Sent", Toast.LENGTH_SHORT);

					
				} catch (Exception e) {
					e.printStackTrace();
			    }
			}
		}


		
		public class AcceptFriendRequestTask extends AsyncTask<String, String, String> {
			@Override
			protected String doInBackground(String... params) {
				// TODO: attempt authentication against a network service.
				String response = "";
				ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
				NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
				
				if(networkInfo != null && networkInfo.isConnected())
				{
					ArrayList<NameValuePair> n = new ArrayList<NameValuePair>(1);
					n.add(new BasicNameValuePair("user", Login.user));
					n.add(new BasicNameValuePair("friend", params[0]));
				
					
					HttpClient httpClient = new DefaultHttpClient();
					HttpPost httppost = new HttpPost("http://softeng.cs.uwosh.edu/students/cs342g2/acceptFriend.php");
					try
					{
						httppost.setEntity(new UrlEncodedFormEntity(n));
						ResponseHandler<String> respondHandler = new BasicResponseHandler();
						response = httpClient.execute(httppost, respondHandler);
					}
					catch(Exception e){
						
					}
				}
				return response;
			}
			
			@Override
			protected void onPostExecute(String resp){
				try {
					Toast.makeText(Friends.this, "Friend Accepted", Toast.LENGTH_SHORT);
					
					
				} catch (Exception e) {
					e.printStackTrace();
			    }
			}
		}



		
		public class ViewFriendLocationTask extends AsyncTask<String, String, String> {
			@Override
			protected String doInBackground(String... params) {
				// TODO: attempt authentication against a network service.
				String response = "";
				ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
				NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
				
				if(networkInfo != null && networkInfo.isConnected())
				{
					ArrayList<NameValuePair> n = new ArrayList<NameValuePair>(1);

					n.add(new BasicNameValuePair("user", params[0]));
				
					
					HttpClient httpClient = new DefaultHttpClient();
					HttpPost httppost = new HttpPost("http://softeng.cs.uwosh.edu/students/cs342g2/getLocation.php");
					try
					{
						httppost.setEntity(new UrlEncodedFormEntity(n));
						ResponseHandler<String> respondHandler = new BasicResponseHandler();
						response = httpClient.execute(httppost, respondHandler);
					}
					catch(Exception e){
						
					}
				}
				return response;
			}
			
			@Override
			protected void onPostExecute(String resp){
				try {

					Intent i = new Intent(Friends.this, Find_Favorite.class);
					i.putExtra("location", resp);
					i.putExtra("name",friendName );
					startActivity(i);
					
				} catch (Exception e) {
					e.printStackTrace();
			    }
			}
		}


	   
}
